package edu.gyc.data.struct.sparsearray;

public class SparseArray {

    public static void main(String[] args) {
        int[][] chessArr1 = new int[11][11];
        //0:无棋子，1黑子 2白子
        chessArr1[1][2] = 1;
        chessArr1[2][3] = 2;
        chessArr1[4][8] = 2;

        System.out.println("原始的二维数组：");
        for (int[] row : chessArr1) {
            for (int data : row) {
                System.out.printf("%d\t", data);
            }
            System.out.println();

        }

        //二维数组转稀疏数组
        int count = 0;
        for (int[] row : chessArr1) {
            for (int data : row) {
                if (data != 0) {
                    count++;
                }
            }


        }
        System.out.println("count=" + count);
        //创建对应的稀疏数组
        int[][] sparseArr = new int[count + 1][3];
        sparseArr[0][0] = 11;
        sparseArr[0][1] = 11;
        sparseArr[0][2] = count;

        //遍历二维数组将非零的值发到稀疏数组
        int n = 0;//n为记录第几个非零数据
        for (int i = 0; i < 11; i++) {
            for (int j = 0; j < 11; j++) {
                if (chessArr1[i][j] != 0) {
                    n++;
                    sparseArr[n][0] = i;
                    sparseArr[n][1] = j;
                    sparseArr[n][2] = chessArr1[i][j];
                }
            }
        }
        //输出稀疏数组
        System.out.println("稀疏数组：");
        for (int i = 0; i < sparseArr.length; i++) {
            System.out.printf("%d\t%d\t%d\t\n", sparseArr[i][0], sparseArr[i][1], sparseArr[i][2]);
        }

        //将稀疏数组还原为二维数组
        int row = sparseArr[0][0];
        int col = sparseArr[0][1];
        int num = sparseArr[0][2];
        int[][] chessArr2 = new int[row][col];
    /*    for (int i = 0; i < row; i++) {
            for (int j = 0; j < col; j++) {
                chessArr2[i][j] = 0;
            }
        }*/

        for (int i = 1; i < sparseArr.length; i++) {
            chessArr2[sparseArr[i][0]][sparseArr[i][1]] = sparseArr[i][2];
        }
        //输出稀疏数组
        System.out.println("还原的二维数组数组：");
        for (int[] row1 : chessArr2) {
            for (int data : row1) {
                System.out.printf("%d\t", data);
            }
            System.out.println();

        }

        System.out.println("数据持久化...");
        MyData data=new MyData();
        data.setSparseArr(sparseArr);
        data.saveData();
        data.readData();

    }



}





